package com.yourenbang.lingyun.transaction.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.yourenbang.lingyun.core.config.datasource.DataSources;
import com.yourenbang.lingyun.core.config.datasource.DynamicDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 多数据源配置
 */
@Configuration
public class DataSourceConfig {

	@Bean
	@ConfigurationProperties("spring.datasource.druid.db-master")
	public DataSource masterDataSource(){
		return DruidDataSourceBuilder.create().build();
	}


	@Bean
	@ConfigurationProperties("spring.datasource.druid.db-slave")
	public DataSource  slaveDataSource(){
		return DruidDataSourceBuilder.create().build();
	}

	@Bean
	@Primary
	public DynamicDataSource dataSource(DataSource masterDataSource, DataSource slaveDataSource) {
		Map<Object, Object> targetDataSources = new HashMap<>();
		targetDataSources.put(DataSources.MASTER_DB, masterDataSource);
		targetDataSources.put(DataSources.SLAVE_DB, slaveDataSource);
		return new DynamicDataSource(masterDataSource, targetDataSources);
	}
}
